#include <iostream>
#include "Socket.hpp"
#include "Protocol.hpp"
#include "Parser.hpp"

void Usage(std::string proc)
{
    std::cerr << "Usage : " << proc << " serverip serverport" << std::endl;
}

// ./tcp_client serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    std::unique_ptr<Socket> client = std::make_unique<TcpSocket>();
    if (client->BuildConnectSocketMethod(serverip, serverport))
    {
        // 连接成功后将 socket 设回阻塞，方便后续的同步 recv/输入交互
        int fd = client->GetSockFd();
        int flags = fcntl(fd, F_GETFL, 0);
        if (flags >= 0)
            fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);

        std::string inbuffer;
        while (true)
        {

            // 1. 构建请求
            Request rq;
            std::cout << "Please Enter X: ";
            std::cin >> rq._x;
            std::cout << "Please Enter Y: ";
            std::cin >> rq._y;
            std::cout << "Please Enter Oper: ";
            std::cin >> rq._oper;

            // 2. 序列化
            std::string jsonstr;
            rq.Serializ(&jsonstr);

            // 3. 打包
            std::string sendstr = Protocol::Package(jsonstr);

            // 4. 发送
            client->Send(sendstr);

            // 5. 接收
            client->Recv(&inbuffer, 100);
            std::string package;
            int n = Protocol::UnPackage(inbuffer, &package);
            if (n > 0)
            {
                Response rp;
                bool r = rp.Deserialize(package);

                if (r)
                {
                    rp.Print();
                }
            }
        }
    }
    return 0;
}